from apps.pay.lzpay.baseViews import *
from apps.interface.client.models import Client
from apps.pay.order.dao import OrderDao
from apps.pay.order.sceneHandle import payReturnScene

class WxPayViewSet(BaseLzpayViewSet):
    
    ''''支付创建'''
    @action(methods=['post'], detail=False)
    def createWxPayforMinipro(self, request):
        params = getRequestParams(request)

        if isEmptyStr(params.get('openid')):
            return Response(response_message('openid字段必填'))
        if isEmptyStr(params.get('clientname')):
            return Response(response_message('clientname字段必填'))
        if not params.get("orderId"):
            return Response(response_message('orderId字段必填'))
        try:
            client_model = Client.objects.get(clientname=params.get('clientname'))
            _order = OrderDao().findOneByOrderId(params.get("orderId"))
            if isEmptyStr(_order.scene):
                return Response(response_message('该订单异常，缺少scene参数'))
            if _order.orderStatus != 'WAIT_PAY':
                return Response(response_modalMessage('待支付的订单才允许支付'))

            # 校验积分
            if _order.realPayIncomes>0:
                if request.user.incomes < _order.realPayIncomes:
                    return Response(response_modalMessage('积分不足，支付失败'))            
            r_params = {
                "signType": self.signType,
                "signSN": self.signSN,
                "encryptSN": self.encryptSN,
                "merchantNo": self.merchantNo,
                "payType": "WX_PAY_JSAPI",
                "bizType": "UNDERLINE",
                "merOrderNo": params.get("orderId"),
                "currency": "CNY",
                "payerId":  params.get('openid'),
                "notifyUrl": client_model.baseUrl + '/api/pay/lzpay/scan/paybackforMinipro/',
                "appId": client_model.appid
            }
            # 设置商品名称
            if _order.content:
                content = json.loads(_order.content)
                if content.get('orderItemList') and len(content.get('orderItemList'))>0:
                    r_params["orderDesc"] = content.get('orderItemList')[0].get('itemName')
                else:
                    r_params["orderDesc"] = "鑫珑名品优选商品"
            else:
                r_params["orderDesc"] = "鑫珑名虚拟商品"
            # 设置商品价格
            realPay = 0
            if client_model.realPay > 0:
                realPay = Decimal(client_model.realPay)
            else:
                realPay = _order.realPay
            r_params["tradeAmount"] = Decimal(realPay)
            # 设置分账参数
            # splitParams = [{"splitMerchantNo":"30104947","splitRate":"0.1"}]
            # r_params["splitJson"] = json.dumps(splitParams)
            
            sign = self.getSign(r_params)
            if sign:
                r_params['sign'] = sign
            else:
                return Response(response_error('获取签名失败'))
            url = "https://scan.lzpay.com/api/scanCode/scanCodePay"
            headers = {'content-type': "application/x-www-form-urlencoded;charset=UTF-8"}
            print('r_params', r_params)
            res = requests.post(url, data=r_params, headers=headers)
            res_content = json.loads(res.content)
            print('res_content', res, res_content)
            if res_content.get('code') == '00':
                data = json.loads(res_content.get('payData'))
                return Response(response_success(data))
            else:
                return Response(response_message(res_content.get('message')))
        except Exception as e:
            print('乐付支付异常', e)
            return Response(response_message('乐付支付异常'))